package net.adetech.cjg.innerservice.controller;


import net.adetech.cjg.innerservice.entity.Apk;
import net.adetech.cjg.innerservice.mapper.ApkDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
public class ApkDownloadController {


    @Autowired
    private HttpServletRequest request;

    @Autowired
    ApkDao apkDao;

    private String getClientIp() {
        String remoteAddr = "";

        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }

        return remoteAddr;
    }


    @RequestMapping(value = "/cjg/downloadApk", produces="application/vnd.android.package-archive")
    public ResponseEntity<byte[]> getApp(HttpServletRequest request,
                                         HttpServletResponse resp) throws IOException {
        String ip = getClientIp();
        List<Apk> apkList = apkDao.getUpdateApkListByIp(ip);
        Apk newApk = apkList.get(0);

        String filename = "cjg-"+newApk.getBbmc()+".apk";
        File f=new File(newApk.getLj());
        InputStream in =null;
        ResponseEntity<byte[]> response=null ;
        try {
            in = new FileInputStream(f);
            byte[] b=new byte[in.available()];
            in.read(b);
            HttpHeaders headers = new HttpHeaders();
            filename = new String(filename.getBytes(),"utf-8");
            //MediaType mt = new MediaType("application/vnd.android.package-archive");
            //headers.setContentType(mt);
            //以下的类型必须要设置，要不不能在android机上正常下载的
            headers.add("Content-Disposition", "attachment;filename="+filename);

            //resp.setContentType("application/vnd.android.package-archive");
            HttpStatus statusCode=HttpStatus.OK;
            response = new ResponseEntity<byte[]>(b, headers, statusCode);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return response;
    }
}
